package com.whale.nangua.pumpkingobang.aty;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.wuziqi.R;
import com.whale.nangua.pumpkingobang.Network.NetworkActivity;
import com.whale.nangua.pumpkingobang.Network.TCP_Network;


public class InitAty extends Activity {
    private ImageButton init_renjibtn;
    private ImageButton init_lanyabtn;
    private ImageButton init_rankbtn;
    private ImageButton init_renrenbtn;
    private ImageButton init_networkbtn;
    private ImageButton init_fupangbtn;
    private InitButtonListener initButtonListener;

    private int width;
    private int height;
    private ImageButton avatarButton;
    private Button login_button, button_confirm, button_cancel, registered_button;
    private PopupWindow loging_pop;
    private PopupWindow registered_pop;
    EditText user;
    EditText pass;
    TextView name_text;
    EditText pass_repeat;
    TCP_Network client;
    static boolean server_flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.init_layout);
        //设置沉浸式标题栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        //通过DisplayMetrics来获取界面大小
        DisplayMetrics dm = getResources().getDisplayMetrics();
        width = dm.widthPixels;
        height = dm.heightPixels;
        initView();

        avatarButton = (ImageButton)findViewById(R.id.avatar_button);
        avatarButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出退出登录提示框
                new AlertDialog.Builder(InitAty.this)
                        .setTitle("退出登录")
                        .setMessage("确定要退出登录吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 退出登录操作
                                logout();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });

    }

    private void initView() {
        initButtonListener = new InitButtonListener();

        init_renjibtn = (ImageButton) findViewById(R.id.init_renjibtn);
        init_lanyabtn = (ImageButton) findViewById(R.id.init_lanyabtn);
        init_networkbtn = (ImageButton) findViewById(R.id.init_networkbtn);
        init_renrenbtn = (ImageButton) findViewById(R.id.init_renrenbtn);
        init_fupangbtn= (ImageButton) findViewById(R.id.init_fupangbtn);
        init_rankbtn = (ImageButton) findViewById(R.id.init_rankbtn);
        init_renrenbtn = (ImageButton) findViewById(R.id.init_renrenbtn);
        initButtonListener = new InitButtonListener();
        init_renjibtn.setOnClickListener(initButtonListener);
        init_lanyabtn.setOnClickListener(initButtonListener);
        init_rankbtn.setOnClickListener(initButtonListener);
        init_networkbtn.setOnClickListener(initButtonListener);
        init_renrenbtn.setOnClickListener(initButtonListener);
        init_fupangbtn.setOnClickListener(initButtonListener);
        init_rankbtn.setOnClickListener(initButtonListener);

        login_button = (Button) findViewById(R.id.login_button);
        registered_button = (Button) findViewById(R.id.registered_button);


        login_button.setOnClickListener(initButtonListener);
        registered_button.setOnClickListener(initButtonListener);

        client =  (TCP_Network) this.getApplication();

    }


    private class InitButtonListener implements View.OnClickListener{
        Intent i ;

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.init_renjibtn) {
                AlertDialog mydialog = new AlertDialog.Builder(InitAty.this).create();
                mydialog.show();
                mydialog.getWindow().setContentView(R.layout.renjichoice_dialog);
                mydialog.getWindow()
                        .findViewById(R.id.renjichoice_jiandan)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                i = new Intent(InitAty.this, RenjiGameAty.class);
                                //设置从右边出现
                                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                                i.putExtra("flag", 1);
                                startActivity(i);
                            }
                        });
                mydialog.getWindow()
                        .findViewById(R.id.renjichoice_kunnan)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                i = new Intent(InitAty.this, RenjiGameAty.class);
                                //设置从右边出现
                                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                                i.putExtra("flag", 2);
                                startActivity(i);
                            }
                        });
                mydialog.getWindow()
                        .findViewById(R.id.renjichoice_chaonan)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                i = new Intent(InitAty.this, RenjiGameAty.class);
                                //设置从右边出现
                                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                                i.putExtra("flag", 3);
                                startActivity(i);
                            }
                        });


                //人人对战
            } else if (id == R.id.init_renrenbtn) {
                i = new Intent(InitAty.this, RenRenGameAty.class);
                //设置从右边出现
                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                startActivity(i);
            } else if (id == R.id.init_lanyabtn) {
                i = new Intent(InitAty.this, BlueToothFindOthersAty.class);
                //设置从右边出现
                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                startActivity(i);
            }  else if (id == R.id.init_networkbtn) {
                if (!server_flag) {
                    server_error();
                    return;
                }
                i = new Intent(InitAty.this, NetworkActivity.class);
                //设置从右边出现
                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                startActivity(i);
            }else if (id == R.id.init_fupangbtn) {

                i = new Intent(InitAty.this, FupanSelectAty.class);
                //设置从右边出现
                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                startActivity(i);
            } else if (id == R.id.init_rankbtn) {
                i = new Intent(InitAty.this, RankAty.class);
                //设置从右边出现
                InitAty.this.overridePendingTransition(R.anim.initactivity_open, 0);
                startActivity(i);
            }else if (id == R.id.login_button) {
                initPop_login();
            } else if (id == R.id.registered_button) {
                initPop_registered();
            } else if (id == R.id.login_confirm) {
                login();
            } else if (id == R.id.registered_confirm) {
                registered();
            } else if (id == R.id.login_cancel) {
                loging_pop.dismiss();
            } else if (id == R.id.registered_cancel) {
                registered_pop.dismiss();
            }
        }
    }
    long lastBackPressed = 0;
    @Override
    public void onBackPressed() {
        //当前时间
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastBackPressed < 2000) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
        }
        lastBackPressed = currentTime;
    }





    private void server_error() {
        final androidx.appcompat.app.AlertDialog.Builder alterDiaglog = new androidx.appcompat.app.AlertDialog.Builder(this);
        alterDiaglog.setTitle("服务器连接失败");
        alterDiaglog.setMessage("无法进行联机对战");
        alterDiaglog.setPositiveButton("确定", null);
        alterDiaglog.show();
    }

    private void registered() {
        String str_login = user.getText().toString();
        String str_password = pass.getText().toString();
        String str_password_repeat = pass_repeat.getText().toString();
        if (!str_password_repeat.equals(str_password))
            Toast.makeText(this, "两次密码输入错误", Toast.LENGTH_SHORT).show();
        else {
            JSONObject object = new JSONObject();
            object.put("function", "registered");
            object.put("username", str_login);
            object.put("password", str_password);
            object = JSONObject.parseObject(client.sendAndReceiveMessage(object.toString()));
            if (object.getBoolean("return")) {
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
                registered_pop.dismiss();
            } else {
                Toast.makeText(this, "注册失败,用户名已存在", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void login() {
        if (!server_flag&&client.Connect_start()) {
            Toast.makeText(this, "服务器连接成功", Toast.LENGTH_SHORT).show();
            server_flag = true;
        } else{
            Toast.makeText(this, "服务器连接失败", Toast.LENGTH_SHORT).show();
            return;
        }

        String str_user = user.getText().toString();
        String str_password = pass.getText().toString();
        JSONObject object = new JSONObject();
        object.put("function", "login");
        object.put("username", str_user);
        object.put("password", str_password);
        object = JSONObject.parseObject(client.sendAndReceiveMessage(object.toString()));
        if (object.getBoolean("return")) {
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            loging_pop.dismiss();

            // 隐藏登录和注册按钮
            login_button.setVisibility(View.GONE);
            registered_button.setVisibility(View.GONE);
            // 显示头像按钮
            avatarButton.setVisibility(View.VISIBLE);
        } else {
            if (object.containsKey("error")&&object.get("error").equals("1"))
                Toast.makeText(this, "登陆失败,用户名不存在", Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(this, "登录失败,密码错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void initPop_login() {
        //绑定xml文件
        View view = View.inflate(this, R.layout.login, null);
        //绑定
        user = (EditText) view.findViewById(R.id.login_useredit);
        pass = (EditText) view.findViewById(R.id.login_passwardedit);

        button_confirm = (Button) view.findViewById(R.id.login_confirm);
        button_confirm.setOnClickListener(initButtonListener);
        button_cancel = (Button) view.findViewById(R.id.login_cancel);
        button_cancel.setOnClickListener(initButtonListener);
        loging_pop = new PopupWindow(view, width, height);
        //获取焦点
        loging_pop.setFocusable(true);
        View rootview = LayoutInflater.from(this).inflate(R.layout.init_layout, null);
        loging_pop.showAsDropDown(rootview, Gravity.CENTER, 0, 0);

    }

    private void initPop_registered() {
        //绑定xml文件
        View view = View.inflate(this, R.layout.registered, null);
        //绑定
        user = (EditText) view.findViewById(R.id.registered_useredit);
        pass = (EditText) view.findViewById(R.id.registered_passwardedit);
        pass_repeat = (EditText) view.findViewById(R.id.registered_passwardedit_repeat);

        button_confirm = (Button) view.findViewById(R.id.registered_confirm);
        button_confirm.setOnClickListener(initButtonListener);
        button_cancel = (Button) view.findViewById(R.id.registered_cancel);
        button_cancel.setOnClickListener(initButtonListener);
        registered_pop = new PopupWindow(view, width, height);
        //获取焦点
        registered_pop.setFocusable(true);
        View rootview = LayoutInflater.from(this).inflate(R.layout.init_layout, null);
        registered_pop.showAsDropDown(rootview, Gravity.CENTER, 0, 0);

    }

    private void logout() {
        // 显示登录和注册按钮
        login_button.setVisibility(View.VISIBLE);
        registered_button.setVisibility(View.VISIBLE);

        // 隐藏头像按钮
        avatarButton.setVisibility(View.GONE);

        // 退出socket连接
        client.Connect_clear();
        server_flag=false;
    }

}
